package com.activenetwork.smlite.business;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.activenetwork.schema.environment.BasicEnvType;
import com.activenetwork.schema.environment.LoginUserType;
import com.activenetwork.smlite.page.LoginPage;
import com.activenetwork.smlite.page.generic.ModelPage;
import com.activenetwork.util.EnvContext;
import com.activenetwork.util.PageLoader;
import com.activenetwork.util.UserPoolStrategy;
import com.activenetwork.util.verification.VerificationAction;

@SuppressWarnings("unused")
public class LoginBusiness {

	private static Logger logger = LoggerFactory.getLogger(LoginBusiness.class);
	private static UserPoolStrategy mainSiteUserPool;
	private String smliteUrl;
	private final WebDriver driver;

	public LoginBusiness(BasicEnvType environment) {
		// Construct Login Users Pools
		if(mainSiteUserPool == null){
			Collection<String[]> userCollection = new ArrayList<String[]>();
			userCollection.clear();
			List<LoginUserType> mainSiteUsers = environment.getMainSite().getUser();
			for(LoginUserType mainSiteUser : mainSiteUsers){
				//String user = mainSiteUser.getAccount()  + "\\" + mainSiteUser.getName();
				String user = mainSiteUser.getName();
				String pwd = mainSiteUser.getPwd();
				userCollection.add(new String[]{user, pwd});
			}
			mainSiteUserPool = new UserPoolStrategy(userCollection);
		}
		
		// Get test environment main site URL
		smliteUrl = environment.getMainSite().getUrl();
		
		// Get web driver from thread local
		driver = EnvContext.webDriverTL.get();
	}

	public void login(VerificationAction...actions) {
		String[] usernameAndPassword = mainSiteUserPool.get();
		String user = usernameAndPassword[0];
		String pwd = usernameAndPassword[1];
		logger.info("Login for thread: " + Thread.currentThread().getName() + " " + user + "\\" + pwd);
		login(user, pwd, smliteUrl, actions);
	}
	
	public void login(String username, String pwd, VerificationAction...actions){
		logger.info("Login on thread: " + Thread.currentThread().toString() + " " + username + "\\" + pwd);
		login(username, pwd, smliteUrl, actions);
	}
	
	private void login(String loginUser, String loginPwd, String url, VerificationAction...actions){
		LoginPage loginPage = LoginPage.getCurrentPage(url);
		
		// Custom verification
		for(VerificationAction action : actions){
			action.verify();
		}
		
		loginPage.inputUserName(loginUser);
		loginPage.inputUserPassword(loginPwd);
		loginPage.clickLogin();
	}
	
	public void logout(){
		try{
			PageLoader.load(ModelPage.class).logout();
			logger.info("Logoff for thread: " + Thread.currentThread().getName());
		}catch(NoSuchElementException e){
			logger.info("Logoff for thread: " + Thread.currentThread().getName() + " failed");
		}
		mainSiteUserPool.release();
	}
	

}
